# -*- coding: utf-8

from django.http import JsonResponse

from django.contrib.auth import authenticate, login
from django.contrib.auth.models import *
from GameServer.models import History

from GameServer.cache import cache

# Create your views here.

# user system


def get_history(username):
    user_history = History.objects.filter(username=username)[0]
    success = user_history.success
    failure = user_history.failure
    score = user_history.score
    return success, failure, score


def end_game_action(action):
    action_type = action['action_type']
    if action_type == 'partner_resign':
        return True
    if action_type == 'partner_peace_answer':
        permission = action['permission']
        if permission == '1':
            return True

def sign_in(request):
    username = request.POST['username']
    password = request.POST['password']
    # online check
    if not cache.can_sign_in(username):
        response = JsonResponse({'username': '_online'})
        return response
    user = authenticate(username=username, password=password)
    if user is None:
        response = JsonResponse({'username': '_unauthorized'})
        return response
    login(request, user)
    cache.update_last_time(username)
    print('%s authorized' % username)
    # print(password)
    cache.do_sign_in(username)
    success, failure, score = get_history(username)
    response = JsonResponse(
        {
            'username': username,
            'success': success,
            'failure': failure,
            'score': score
        }
    )
    return response


def sign_up(request):
    # create user
    username = request.POST['username']
    password = request.POST['password']
    email = request.POST['email']
    if History.objects.filter(username=username).__len__() != 0:
        response = JsonResponse({'username': '_existed'})
        return response
    user = User.objects.create_user(username, email, password)
    user.save()
    # init history
    history = History(username=username, success=0, failure=0, score=100)
    history.save()
    response = JsonResponse({'username': username})
    return response


def sign_out(request):
    username = request.POST['username']
    cache.do_sign_out(username)
    response = JsonResponse({'result': 'ok'})
    return response


def reset_password(request):
    username = request.POST['username']
    old_password = request.POST['old_password']
    new_password = request.POST['new_password']
    user = auth.authenticate(username=username, password=old_password)
    print(old_password)
    if user is None:
        response = JsonResponse({'result': '_invalid_password'})
        return response
    print('%s authorized' % username)
    user.set_password(new_password)
    user.save()
    print('reset password for %s' % username)
    response = JsonResponse({'result': 'ok'})
    return response

# partner system


def set_ready(request):
    username = request.POST['username']
    # online check
    if not cache.get_online_state(username):
        raise RuntimeError('user offline')
    cache.update_last_time(username)
    self_ready = int(request.POST['ready'])
    partner_name = cache.partner_users.get(username)[0]
    partner_ready = cache.partner_users.get(username)[2]
    cache.partner_users.set(username, [partner_name, self_ready, partner_ready])
    cache.partner_users.set(partner_name, [username, partner_ready, self_ready])
    response = JsonResponse({'result': 'ok'})
    return response


def change_partner(request):
    username = request.POST['username']
    # online check
    if not cache.get_online_state(username):
        raise RuntimeError('user offline')
    cache.update_last_time(username)
    partner = cache.do_change_partner(username)
    if partner is None:
        response = JsonResponse({"name": "_none"})
    # get partner data
    partner_history = History.objects.filter(username=username)[0]
    success = partner_history.success
    failure = partner_history.failure
    score = partner_history.score
    # render response
    values = {
        "name": partner,
        "success": success,
        "failure": failure,
        "score": score
    }
    response = JsonResponse(values)
    return response


def flush_partner(request):
    # get data
    username = request.POST['username']
    print(username + ' flush partner')
    client_partner_ready = int(request.POST['partner_ready'])
    has_partner = int(request.POST['has_partner'])
    # online check
    if not cache.get_online_state(username):
        response = JsonResponse({"action_type": "_offline"})
        return response
    cache.update_last_time(username)
    # get first partner
    if has_partner == 0:
        partner = cache.do_first_partner(username)
        if partner is None:
            values = {'action_type': 'nothing'}
            response = JsonResponse(values)
            return response
        partner_history = History.objects.filter(username=username)[0]
        success = partner_history.success
        failure = partner_history.failure
        score = partner_history.score
        values = {
            'action_type': 'partner_changed',
            'name': partner,
            'success': success,
            'failure': failure,
            'score': score
        }
        response = JsonResponse(values)
        return response
    elif has_partner == 1:
        partner = cache.partner_users.get(username)[0]
        self_ready = cache.partner_users.get(username)[1]
        current_partner_ready = cache.partner_users.get(username)[2]
    # examine partner time out
    if not cache.get_online_state(partner):
        cache.do_sign_out(partner)
        partner = None
    # get new partner
    if partner is None:
        partner = cache.do_change_partner(username)
        # cannot find new partner
        if partner is None:
            # score = History.objects.filter(username=username)[0].score
            # cache.partner_users.pop(username)
            # cache.waiting_users.set(username, score)
            values = {
                'action_type': 'partner_changed',
                'name': '_none',
            }
            response = JsonResponse(values)
            return response
        partner_history = History.objects.filter(username=username)[0]
        success = partner_history.success
        failure = partner_history.failure
        score = partner_history.score
        values = {
            'action_type': 'partner_changed',
            'name': partner,
            'success': success,
            'failure': failure,
            'score': score
        }
        response = JsonResponse(values)
        return response
    # examine ready
    if self_ready == 1 and current_partner_ready == 1:
        role = cache.do_start_game(username)
        values = {
            'action_type': 'game_start',
            'partner': partner,
            'role': role
        }
        response = JsonResponse(values)
        return response
    if current_partner_ready == client_partner_ready:
        values = {'action_type': 'nothing'}
    else:
        values = {
            'action_type': 'partner_ready',
            'partner_ready': current_partner_ready
        }
    response = JsonResponse(values)
    return response


# online game system

def new_step(request):
    username = request.POST['username']
    x = int(request.POST['x'])
    y = int(request.POST['y'])
    # online check
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    # update cache
    cache.do_new_step(username, x, y)
    response = JsonResponse({'result': 'ok'})
    return response


def resign(request):
    username = request.POST['username']
    partner = cache.playing_users.get(username)[0]
    # online check
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    # history
    self_history = History.objects.filter(username=username)[0]
    self_history.failure += 1
    self_history.save()
    partner_history = History.objects.filter(username=username)[0]
    partner_history.success += 1
    partner_history.save()
    # update cache
    cache.do_resign(username)
    cache.do_end_game(username)
    response = JsonResponse({'result': 'ok'})
    return response


def retract_ask(request):
    username = request.POST['username']
    # online check
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    cache.do_retract_ask(username)
    response = JsonResponse({'result': 'ok'})
    return response


def retract_answer(request):
    username = request.POST['username']
    permission = request.POST['permission']
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    cache.do_retract_answer(username, permission)
    response = JsonResponse({'result': 'ok'})
    return response


def peace_ask(request):
    username = request.POST['username']
    # online check
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    cache.do_peace_ask(username)
    response = JsonResponse({'result': 'ok'})
    return response


def peace_answer(request):
    username = request.POST['username']
    permission = request.POST['permission']
    if not cache.get_online_state(username):
        response = JsonResponse({'result': '_offline'})
        return response
    cache.update_last_time(username)
    cache.do_peace_answer(username, permission)
    if permission == '1':
        cache.do_end_game(username)
    response = JsonResponse({'result': 'ok'})
    return response


def flush_game(request):
    username = request.POST['username']
    print(username + ' flush game')
    if not cache.get_online_state(username):
        response = JsonResponse({'action_type': '_offline'})
        return response
    cache.update_last_time(username)
    # end game
    action = cache.get_action(username)
    print(action)
    if end_game_action(action):
        cache.do_end_game(username)
    # return response
    response = JsonResponse(action)
    return response
